package org.gntc.prayer.myprayer;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.gntc.prayer.R;
import org.gntc.prayer.db.PrayerDBMngr;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;


public class PrayerListActivity extends ListActivity
{
	/** Called when the activity is first created. */
	
	public final static String ITEM_LINE_1 = "title";
	public final static String ITEM_LINE_2 = "date";
	
	private PrayerDBMngr m_PrayerDBMngr;
	
	/**
	 * Create list item
	 * @param strTitle
	 * @param strDate
	 * @return
	 */
	public Map<String, ?> createListItem(String strID, String strTitle, String strDate)
	{
		Map<String, String> item = new HashMap<String, String>();
		
		item.put(ITEM_LINE_1, strTitle);
		item.put(ITEM_LINE_2, strDate);
		item.put("id", strID);
		
		return item;
	}
	
	/**
	 * onCreate
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.prayer_list);
	    
	    // DB Open
	    openDB();
	}
	
	/**
	 * onResume
	 */
	@Override
	public void onResume()
	{
		super.onResume();
		
		// Prayer 목록 구하기
	    getPrayerList();
	    
	    // debug
	    //m_PrayerDBMngr.debug_allTableView();
	}
	
	/**
	 * DB Open
	 */
	private void openDB()
	{
		m_PrayerDBMngr = new PrayerDBMngr(PrayerListActivity.this);
		
		try
		{
			m_PrayerDBMngr.open();
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * onDestroy
	 */
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		
		// DB close
		m_PrayerDBMngr.close();
	}
	
	/**
	 * Menu
	 */
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	getMenuInflater().inflate(R.menu.prayer_list_menu, menu);
    	return true;
    }
	
	/**
	 * Menu selected
	 */
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch( item.getItemId() )
    	{
    	case R.id.prayer_list_btn_add :
    		// Call add activity
    		Intent intent = new Intent(PrayerListActivity.this, PrayerEditActivity.class);
			startActivity(intent);
    		break;
    		
    	default :
    		return false;
    	}
    	
    	return true;
    }
	
	/**
	 * Prayer 목록 구하기
	 */
	public void getPrayerList()
	{
		/*
		 " SELECT ";
				" p._id,";
				" p.categoryid,";
				" p.prayer,";
				" p.setalarm,";
				" c.catename, ";
				" p.regdate ";
		  " FROM ";
				" prayer_tbl p ";
				" INNER JOIN ";
				" prayer_category_tbl c";
				" ON ";
				" p.categoryid = c._id ";
		  " ORDER BY ";
		 		" c.catename ASC, ";
		 		" p._id DESC ";
		*/
		
		// Prayer 목록
		PrayerListAdapter adapter = new PrayerListAdapter(this);
		Map<Integer, List<Map<String, ?>>> mapSection = new HashMap<Integer, List<Map<String, ?>>>();
		
		Cursor cursor = m_PrayerDBMngr.getAllPrayerList();
		cursor.moveToFirst();
		
		int nTotalCnt = cursor.getCount();
		int nCateID = 0;
		int nOldCateID = 0;
		int nSectionIdx = 0;
		String strCateName = "";
		
		if (nTotalCnt > 0)
		{
			for (int i = 0; i < nTotalCnt; i++)
			{
				// Category ID
				nCateID = cursor.getInt(1);
				
				if (i == 0)
				{
					// 첫 레코드인 경우
					List<Map<String, ?>> prayerData = new LinkedList<Map<String, ?>>();
					
					mapSection.put(nSectionIdx, prayerData);
					
					nOldCateID = nCateID;
					strCateName = cursor.getString(4);
				}
				
				if (nOldCateID == nCateID)
				{
					// 같은 Category
					List<Map<String, ?>> tmpPrayerData = mapSection.get(nSectionIdx);
					tmpPrayerData.add( createListItem( cursor.getString(0), cursor.getString(2), cursor.getString(5) ) );
				}
				else
				{
					// section 추가
					List<Map<String, ?>> tmpPrayerData = mapSection.get(nSectionIdx);
					
					SimpleAdapter sa = new SimpleAdapter(this,
														 tmpPrayerData,
														 R.layout.list_item,
														 new String[] {ITEM_LINE_1, ITEM_LINE_2},
														 new int[] {R.id.list_item_line1, R.id.list_item_line2});
					
					adapter.addSection(strCateName, sa);
					
					// Category ID 재설정
					nOldCateID = nCateID;
					strCateName = cursor.getString(4);
					
					nSectionIdx++;
					
					List<Map<String, ?>> prayerData = new LinkedList<Map<String, ?>>();
					mapSection.put(nSectionIdx, prayerData);
					
					prayerData.add( createListItem( cursor.getString(0), cursor.getString(2), cursor.getString(5) ) );
				}
				
				cursor.moveToNext();
			}
			
			// 마지막 section 추가
			List<Map<String, ?>> tmpPrayerData = mapSection.get(nSectionIdx);
			
			SimpleAdapter sa = new SimpleAdapter(this,
												 tmpPrayerData,
												 R.layout.list_item,
												 new String[] {ITEM_LINE_1, ITEM_LINE_2},
												 new int[] {R.id.list_item_line1, R.id.list_item_line2});
	
			adapter.addSection(strCateName, sa);
		}
		
		// Close cursor
		cursor.close();
		
		setListAdapter(adapter);
	}
	
	/**
	 * List item select event
	 */
	@Override
	protected void onListItemClick(ListView listview, View view, int position, long id)
	{
		//Toast.makeText(PrayerListActivity.this, "list selected - " + position + ", id : " + id, Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(PrayerListActivity.this, PrayerViewActivity.class);
		intent.putExtra("id", id);
		startActivity(intent);
	}
	
}
